package com.airbat.prize.modules.base.controller.resource;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.airbat.prize.common.pojo.CommonResult;
import com.airbat.prize.common.pojo.PageResult;
import com.airbat.prize.common.util.servlet.ServletUtils;
import com.airbat.prize.excel.core.util.ExcelUtils;
import com.airbat.prize.modules.base.controller.resource.vo.*;
import com.airbat.prize.modules.base.convert.resource.BaseResourceConvert;
import com.airbat.prize.modules.base.dal.dataobject.resource.BaseResourceDO;
import com.airbat.prize.modules.base.service.resource.BaseResourceService;
import com.airbat.prize.operatelog.core.annotations.OperateLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static com.airbat.prize.common.pojo.CommonResult.success;
import static com.airbat.prize.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "文件资源")
@RestController
@RequestMapping("/base/resource")
@Validated
public class BaseResourceController {

    @Resource
    private BaseResourceService resourceService;

    @PostMapping("/upload")
    @ApiOperation("上传文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件附件", required = true, dataTypeClass = MultipartFile.class),
            @ApiImplicitParam(name = "name", value = "文件名称", required = false, example = "yudaoyuanma.png", dataTypeClass = String.class),
            @ApiImplicitParam(name = "type", value = "文件类型", required = false, example = "1", dataTypeClass = Integer.class)
    })
    public CommonResult<String> uploadFile(@RequestParam("file") MultipartFile file,
                                           @RequestParam("name") String name,
                                           @RequestParam("type") Integer type) throws IOException {
        return success(resourceService.createFile(name, type, IoUtil.readBytes(file.getInputStream())));
    }

    @PostMapping("/create")
    @ApiOperation("创建文件资源")
    @PreAuthorize("@ss.hasPermission('base:resource:create')")
    public CommonResult<String> createResource(@Valid @RequestBody BaseResourceCreateReqVO createReqVO) {
        return success(resourceService.createResource(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新文件资源")
    @PreAuthorize("@ss.hasPermission('base:resource:update')")
    public CommonResult<Boolean> updateResource(@Valid @RequestBody BaseResourceUpdateReqVO updateReqVO) {
        resourceService.updateResource(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件资源")
    @ApiImplicitParam(name = "id", value = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:resource:delete')")
    public CommonResult<Boolean> deleteResource(@RequestParam("id") String id) {
        resourceService.deleteResource(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得文件资源")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('base:resource:query')")
    public CommonResult<BaseResourceRespVO> getResource(@RequestParam("id") String id) {
        BaseResourceDO resource = resourceService.getResource(id);
        return success(BaseResourceConvert.INSTANCE.convert(resource));
    }

    @GetMapping("/list")
    @ApiOperation("获得文件资源列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('base:resource:query')")
    public CommonResult<List<BaseResourceRespVO>> getResourceList(@RequestParam("ids") Collection<String> ids) {
        List<BaseResourceDO> list = resourceService.getResourceList(ids);
        return success(BaseResourceConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得文件资源分页")
    @PreAuthorize("@ss.hasPermission('base:resource:query')")
    public CommonResult<PageResult<BaseResourceRespVO>> getResourcePage(@Valid BaseResourcePageReqVO pageVO) {
        PageResult<BaseResourceDO> pageResult = resourceService.getResourcePage(pageVO);
        return success(BaseResourceConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出文件资源 Excel")
    @PreAuthorize("@ss.hasPermission('base:resource:export')")
    @OperateLog(type = EXPORT)
    public void exportResourceExcel(@Valid BaseResourceExportReqVO exportReqVO,
                                    HttpServletResponse response) throws IOException {
        List<BaseResourceDO> list = resourceService.getResourceList(exportReqVO);
        // 导出 Excel
        List<BaseResourceExcelVO> datas = BaseResourceConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "文件资源.xls", "数据", BaseResourceExcelVO.class, datas);
    }

    @ApiOperation("下载资源文件")
    @GetMapping("/download")
    @PreAuthorize("@ss.hasPermission('base:resource:download')")
    public void downloadCodegen(@RequestParam("resourceId") String resourceId,
                                HttpServletResponse response) throws IOException {
        BaseResourceDO baseResourceDO = resourceService.getResource(resourceId);
        if (baseResourceDO != null && FileUtil.exist(baseResourceDO.getPath())) {
            byte[] bytes = FileUtil.readBytes(baseResourceDO.getPath());
            ServletUtils.writeAttachment(response, baseResourceDO.getName(), bytes);
        }
    }

}
